#pragma once

#include <iostream>
#include <cstring>
#include <cerrno>
#include <functional>
#include <unordered_map>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include "Ringqueue.hpp"
#include "LockGuard.hpp"
#include "Thread.hpp"

namespace Alpaca
{
    const uint16_t defaultport = 8080;
    using func_t = std::function<std::string(std::string)>;
    class UdpServer
    {
    public:
        UdpServer(int port = defaultport)
            : _port(port)
        {
            pthread_mutex_init(&lock, nullptr);
            p = new Thread(1, std::bind(&UdpServer::Recv, this));
            c = new Thread(2, std::bind(&UdpServer::Broadcast, this));
        }
        ~UdpServer()
        {
            pthread_mutex_destroy(&lock);
            c->join();
            p->join();

            delete c;
            delete p;
        }
        void Start()
        {
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cout << "create socket error: " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }

            std::cout << "create socket success: " << _sock << std::endl;

            struct sockaddr_in local;
            bzero(&local, sizeof local);
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(_sock, (sockaddr *)&local, sizeof(local)))
            {
                std::cout << "bind socket error: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success" << std::endl;

            c->run();
            p->run();
        }

        void addUser(const std::string &name, const struct sockaddr_in &peer)
        {
            LockGuard lg(&lock);
            if (!OnlineUser.count(name))
                OnlineUser[name] = peer;
        }

        void Recv()
        {
            char buffer[1024];
            while (true)
            {
                // 接收信息
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
                if (n > 0)
                    buffer[n] = '\0';
                else
                    continue;

                // 提取客户端信息
                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t port = ntohs(peer.sin_port);
                std::cout << "get message from " << clientip << "-" << port << ": " << buffer << std::endl;

                std::string name = clientip;
                name += "-";
                name += std::to_string(port);

                addUser(name, peer);

                std::string message = name + "echo# " + buffer;
                rq.push(message);
            }
        }

        void Broadcast()
        {
            while (true)
            {
                std::string sendstring;
                rq.pop(&sendstring);
                std::vector<sockaddr_in> v;
                {
                    LockGuard lockguard(&lock);
                    for (auto &usr : OnlineUser)
                    {
                        v.push_back(usr.second);
                    }
                }
                for (auto &usr : v)
                {
                    sendto(_sock, sendstring.c_str(), sendstring.size(), 0, (sockaddr *)&usr, sizeof(usr));
                }
            }
        }

    private:
        int _sock;
        uint16_t _port;
        pthread_mutex_t lock;
        std::unordered_map<std::string, struct sockaddr_in> OnlineUser;
        RingQueue<std::string> rq;

        Thread *c;
        Thread *p;
    };
}